package com.gl.basis.zuul.filter;

import com.gl.basis.zuul.config.ZuulConfig;
import com.gl.basis.zuul.util.UrlPattern;
import com.gl.basis.zuul.util.ZuulUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 * 白名单管理
 *
 */
@Slf4j
@Component
public class WhiteListFilter extends ZuulFilter {

    private ZuulConfig zuulConfig;

    public WhiteListFilter(ZuulConfig zuulConfig) {
        this.zuulConfig = zuulConfig;
    }

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return RequestContext.getCurrentContext().sendZuulResponse();
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        String path = context.getRequest().getServletPath();
        if (!matchWhiteList(path)) {
            ZuulUtil.failFast(context, 404,404,"未知的请求地址");
        }
        return null;
    }

    private boolean matchWhiteList(String path) {
        // 没配置代表不实用白名单功能
        if (CollectionUtils.isEmpty(zuulConfig.getWhiteListAll())) {
            return true;
        }
        String pattern =
            zuulConfig.getWhiteListAll().stream().filter(o -> UrlPattern.isMatch(path,o)).findFirst().orElse(null);
        if (StringUtils.isEmpty(pattern)) {
            log.info("msg1=请求[{}]非法，没有找到可匹配的白名单规则: {}", path, zuulConfig.getWhiteListAll());
            return false;
        }
        log.info("msg1=为请求[{}]找到可匹配的白名单规则[{}]", path, pattern);
        return true;
    }
    
    
    
}
